package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author 李智勇
 * @data 2025/10/17 19:53
 */

@Slf4j
@Aspect
@Component
public class LogRecordAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Pointcut("@annotation(com.qk.management.aop.anno.LogAnno)")
    public void pt() {
    }
    @Around("pt()")
    public Object log(ProceedingJoinPoint pjp) {
        Object returnValue = null;
        try {
            long startTime = System.currentTimeMillis();
            returnValue = pjp.proceed();
            long endTime = System.currentTimeMillis();
            Integer userId = CurrentUserContextHolders.get();
            String className = pjp.getTarget().getClass().getName();
            String methodName = pjp.getSignature().getName();
            Object[] args = pjp.getArgs();
            String params = JSONUtil.toJsonStr(args);
            String result = JSONUtil.toJsonStr(returnValue);
            OperateLog operateLog = OperateLog.builder()
                    .returnValue( result)
                    .methodParams(params)
                    .methodName(methodName)
                    .className( className)
                    .operateUserId(userId)
                    .operateTime(LocalDateTime.now())
                    .costTime(endTime - startTime)
                    .build() ;
            try {
                operateLogMapper.insert(operateLog);
            } catch (Exception e) {
                log.error("操作日志写入数据库失败:{}", e.getMessage());
            }
        } catch (Throwable e) {
            CommonException.throwCommonException(ParamEnum.OPERATE_ERROR);
            log.error("操作失败:{}", e.getMessage());
        }
        return returnValue;
    }
}
